const bcrypt = require("bcrypt");
const { pbkdf2 } = require("crypto");

/**
 * 生成随机字符串
 * @param {Number} round 数值越大生成随机字符串复杂度越高，默认值 10
 * @returns
 */
const fetchSalt = (round = 10) => {
  return bcrypt.genSalt(round);
};
const getSalt = (rounds = 32) => {
  return pbkdf2.genSalt(rounds);
};

module.exports = {
  ciphertext: async (plaintext, round = 10) => {
    try {
      const salt = await fetchSalt(round);
      const result = await bcrypt.hash(plaintext, salt);
      return Promise.resolve(result);
    } catch (error) {
      return Promise.reject(error);
    }
  },

  getCiphertext: async (plaintext, round = 256) => {
    try {
      const salt = getSalt(round);
      const derivedKey = await pbkdf2.hash(plaintext, salt, 10000, 64, "sha1");
      return Promise.resolve(derivedKey.toString("base64"));
    } catch (error) {
      return Promise.reject(error);
    }
  },

  /**
   * 检查是否匹配
   * @param {String} inputText 用户输入的密码
   * @param {String} storeText 数据库中的密码
   * @returns
   */
  compare: (inputText, storeText) => {
    return bcrypt.compare(inputText, storeText);
  },

  handleToCompare: (inputText, storeText) => {
    return pbkdf2.compare(storeText, inputText, 10000, 64, "sha256");
  },
};
